<template>
  <div class="booking-management">
    <h2>{{ $t('message.bookingManagement') }}</h2>
    
    <div class="booking-actions">
      <el-button type="primary" @click="openAddBookingDialog">{{ $t('message.createBooking') }}</el-button>
    </div>
    
    <el-table
      :data="bookings"
      style="width: 100%"
      :default-sort="{ prop: 'createdAt', order: 'descending' }"
      table-layout="fixed"
    >
      <el-table-column :label="$t('message.bookingId')" width="180" show-overflow-tooltip align="left" header-align="left">
        <template #default="scope">
          <div class="table-cell-content">{{ scope.row.bookingId }}</div>
        </template>
      </el-table-column>
      <el-table-column :label="$t('message.scheduleId')" width="150" align="left" header-align="left">
        <template #default="scope">
          <div class="table-cell-content">{{ scope.row.scheduleId }}</div>
        </template>
      </el-table-column>
      <el-table-column :label="$t('message.studentId')" width="120" align="left" header-align="left">
        <template #default="scope">
          <div class="table-cell-content">{{ scope.row.studentId }}</div>
        </template>
      </el-table-column>
      <el-table-column :label="$t('message.parentId')" width="120" align="left" header-align="left">
        <template #default="scope">
          <div class="table-cell-content">{{ scope.row.parentId }}</div>
        </template>
      </el-table-column>
      <el-table-column :label="$t('message.status')" width="120" align="left" header-align="left">
        <template #default="scope">
          <div class="table-cell-content">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusLabel(scope.row.status) }}
            </el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column :label="$t('message.bookingTime')" width="180" align="left" header-align="left">
        <template #default="scope">
          <div class="table-cell-content">{{ formatDate(scope.row.bookingTime) }}</div>
        </template>
      </el-table-column>
      <el-table-column :label="$t('message.actions')" width="250" align="left" header-align="left">
        <template #default="scope">
          <el-button size="small" @click="viewBooking(scope.row)">{{ $t('message.view') }}</el-button>
          <el-button size="small" @click="editBooking(scope.row)">{{ $t('message.edit') }}</el-button>
          <el-button 
            size="small" 
            :type="getActionTypeByStatus(scope.row.status)"
            @click="updateBookingStatus(scope.row)"
          >
            {{ getActionTextByStatus(scope.row.status) }}
          </el-button>
          <el-button size="small" type="danger" @click="deleteBooking(scope.row.bookingId)">{{ $t('message.delete') }}</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 查看/编辑预约对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
    >
      <el-form :model="bookingForm" :rules="bookingRules" ref="bookingFormRef" label-width="120px">
        <el-form-item :label="$t('message.scheduleId')" prop="scheduleId">
          <el-select 
            v-model="bookingForm.scheduleId" 
            :placeholder="$t('message.pleaseSelectSchedule')" 
            style="width: 100%"
            :disabled="isView"
          >
            <el-option
              v-for="schedule in availableSchedules"
              :key="schedule.scheduleId"
              :label="`${schedule.courseName} (${formatDateTime(schedule.startTime)} - ${formatDateTime(schedule.endTime)})`"
              :value="schedule.scheduleId"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('message.studentId')" prop="studentId">
          <el-input 
            v-model="bookingForm.studentId" 
            :placeholder="$t('message.pleaseEnterStudentId')"
            :disabled="isView"
          ></el-input>
        </el-form-item>
        <el-form-item :label="$t('message.parentId')" prop="parentId">
          <el-input 
            v-model="bookingForm.parentId" 
            :placeholder="$t('message.pleaseEnterParentId')"
            :disabled="isView"
          ></el-input>
        </el-form-item>
        <el-form-item :label="$t('message.status')" prop="status">
          <el-select 
            v-model="bookingForm.status" 
            :placeholder="$t('message.pleaseSelectStatus')" 
            style="width: 100%"
            :disabled="isView"
          >
            <el-option
              v-for="status in statusOptions"
              :key="status.value"
              :label="status.label"
              :value="status.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer" v-if="!isView">
          <el-button @click="dialogVisible = false">{{ $t('message.cancel') }}</el-button>
          <el-button type="primary" @click="saveBooking">{{ $t('message.confirm') }}</el-button>
        </span>
        <span class="dialog-footer" v-else>
          <el-button type="primary" @click="dialogVisible = false">{{ $t('message.close') }}</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, reactive } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useI18n } from 'vue-i18n';
import { useAuthStore } from '@/stores/auth';

export default {
  name: 'BookingManagement',
  setup() {
    const { t } = useI18n();
    const authStore = useAuthStore();
    
    // 预约数据
    const bookings = ref([]);
    const availableSchedules = ref([]);
    
    // 对话框相关
    const dialogVisible = ref(false);
    const dialogTitle = ref('');
    const isEdit = ref(false);
    const isView = ref(false);
    
    // 预约表单数据
    const bookingForm = reactive({
      bookingId: '',
      scheduleId: '',
      studentId: '',
      parentId: '',
      status: 'PENDING'
    });
    
    const bookingFormRef = ref();
    
    // 选项数据
    const statusOptions = ref([
      { value: 'PENDING', label: t('message.pending') },
      { value: 'CONFIRMED', label: t('message.confirmed') },
      { value: 'COMPLETED', label: t('message.completed') },
      { value: 'CANCELLED', label: t('message.cancelled') }
    ]);
    
    // 表单验证规则
    const bookingRules = {
      scheduleId: [
        { required: true, message: t('message.pleaseSelectSchedule'), trigger: 'change' }
      ],
      studentId: [
        { required: true, message: t('message.pleaseEnterStudentId'), trigger: 'blur' }
      ],
      parentId: [
        { required: true, message: t('message.pleaseEnterParentId'), trigger: 'blur' }
      ],
      status: [
        { required: true, message: t('message.pleaseSelectStatus'), trigger: 'change' }
      ]
    };
    
    // 获取预约列表
    const loadBookings = async () => {
      try {
        const isParent = authStore.user?.roleId === 'PARENT';
        const isTeacher = authStore.user?.roleId === 'TEACHER';
        
        let apiUrl = '/api/admin/bookings';
        if (isParent) {
          apiUrl = `/api/parent/bookings?parentId=${authStore.user.userId}`;
        } else if (isTeacher) {
          apiUrl = `/api/teacher/bookings?teacherId=${authStore.user.userId}`;
        }
        
        const response = await fetch(apiUrl, {
          headers: {
            'Authorization': `Bearer ${authStore.token}`,
            'Content-Type': 'application/json'
          }
        });
        
        if (response.ok) {
          const bookingData = await response.json();
          
          // 规范化预约数据以确保与表格列定义匹配
          bookings.value = bookingData.map(booking => ({
            bookingId: booking.bookingId || booking.booking_id || booking.id,
            scheduleId: booking.scheduleId || booking.schedule_id,
            studentId: booking.studentId || booking.student_id,
            parentId: booking.parentId || booking.parent_id,
            status: booking.status,
            bookingTime: booking.bookingTime || booking.booking_time || booking.create_time,
            amount: booking.amount,
            createdAt: booking.createdAt || booking.created_at || booking.create_time,
            updatedAt: booking.updatedAt || booking.updated_at || booking.update_time
          }));
        } else {
          ElMessage.error(t('message.failedToLoadBookings'));
        }
      } catch (error) {
        console.error('Error loading bookings:', error);
        ElMessage.error(t('message.failedToLoadBookings'));
      }
    };
    
    // 获取可用排课
    const loadAvailableSchedules = async () => {
      try {
        const response = await fetch('/api/admin/schedules', {
          headers: {
            'Authorization': `Bearer ${authStore.token}`,
            'Content-Type': 'application/json'
          }
        });
        
        if (response.ok) {
          availableSchedules.value = await response.json();
        }
      } catch (error) {
        console.error('Error loading schedules:', error);
      }
    };
    
    // 打开添加预约对话框
    const openAddBookingDialog = () => {
      isEdit.value = false;
      isView.value = false;
      dialogTitle.value = t('message.createBooking');
      resetForm();
      // 如果是家长，自动填入家长ID
      if (authStore.user?.roleId === 'PARENT') {
        bookingForm.parentId = authStore.user.userId;
      }
      dialogVisible.value = true;
    };
    
    // 查看预约
    const viewBooking = (booking) => {
      isEdit.value = false;
      isView.value = true;
      dialogTitle.value = t('message.viewBooking');
      // 复制预约数据到表单，确保属性映射正确
      Object.assign(bookingForm, {
        bookingId: booking.bookingId || booking.booking_id || booking.id,
        scheduleId: booking.scheduleId || booking.schedule_id,
        studentId: booking.studentId || booking.student_id,
        parentId: booking.parentId || booking.parent_id,
        status: booking.status
      });
      dialogVisible.value = true;
    };
    
    // 编辑预约
    const editBooking = (booking) => {
      isEdit.value = true;
      isView.value = false;
      dialogTitle.value = t('message.editBooking');
      // 复制预约数据到表单，确保属性映射正确
      Object.assign(bookingForm, {
        bookingId: booking.bookingId || booking.booking_id || booking.id,
        scheduleId: booking.scheduleId || booking.schedule_id,
        studentId: booking.studentId || booking.student_id,
        parentId: booking.parentId || booking.parent_id,
        status: booking.status
      });
      dialogVisible.value = true;
    };
    
    // 删除预约
    const deleteBooking = async (bookingId) => {
      try {
        await ElMessageBox.confirm(
          t('message.confirmDeleteBooking'),
          t('message.warning'),
          {
            confirmButtonText: t('message.confirm'),
            cancelButtonText: t('message.cancel'),
            type: 'warning'
          }
        );
        
        const response = await fetch(`/api/admin/bookings/${bookingId}`, {
          method: 'DELETE',
          headers: {
            'Authorization': `Bearer ${authStore.token}`,
            'Content-Type': 'application/json'
          }
        });
        
        if (response.ok) {
          ElMessage.success(t('message.deleteBookingSuccess'));
          loadBookings(); // 重新加载预约
        } else {
          ElMessage.error(t('message.deleteBookingFailed'));
        }
      } catch (error) {
        console.error('Error deleting booking:', error);
      }
    };
    
    // 更新预约状态
    const updateBookingStatus = async (booking) => {
      try {
        let newStatus = '';
        let actionText = '';
        
        // 根据当前状态确定可执行的操作
        if (booking.status === 'PENDING') {
          newStatus = 'CONFIRMED';
          actionText = t('message.confirm');
        } else if (booking.status === 'CONFIRMED') {
          newStatus = 'COMPLETED';
          actionText = t('message.complete');
        } else if (booking.status === 'CANCELLED') {
          newStatus = 'PENDING';
          actionText = t('message.reactivate');
        } else {
          // 其他情况，如需要取消
          newStatus = 'CANCELLED';
          actionText = t('message.cancel');
        }
        
        await ElMessageBox.confirm(
          `${actionText} ${t('message.bookingConfirm')}?`,
          t('message.warning'),
          {
            confirmButtonText: t('message.confirm'),
            cancelButtonText: t('message.cancel'),
            type: 'warning'
          }
        );
        
        // 更新预约状态
        const response = await fetch(`/api/booking/${booking.bookingId}/status`, {
          method: 'PUT',
          headers: {
            'Authorization': `Bearer ${authStore.token}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ status: newStatus })
        });
        
        if (response.ok) {
          ElMessage.success(`${actionText}${t('message.successSuffix')}`);
          loadBookings(); // 重新加载预约
        } else {
          ElMessage.error(`${actionText}${t('message.failureSuffix')}`);
        }
      } catch (error) {
        console.error('Error updating booking status:', error);
      }
    };
    
    // 保存预约
    const saveBooking = async () => {
      try {
        await bookingFormRef.value.validate();
        
        let response;
        if (isEdit.value) {
          // 更新预约
          response = await fetch(`/api/booking/${bookingForm.bookingId}`, {
            method: 'PUT',
            headers: {
              'Authorization': `Bearer ${authStore.token}`,
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(bookingForm)
          });
        } else {
          // 创建预约
          response = await fetch('/api/booking', {
            method: 'POST',
            headers: {
              'Authorization': `Bearer ${authStore.token}`,
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(bookingForm)
          });
        }
        
        if (response.ok) {
          ElMessage.success(isEdit.value ? t('message.updateBookingSuccess') : t('message.createBookingSuccess'));
          dialogVisible.value = false;
          loadBookings(); // 重新加载预约
        } else {
          const errorData = await response.json();
          ElMessage.error(errorData.message || (isEdit.value ? t('message.updateBookingFailed') : t('message.createBookingFailed')));
        }
      } catch (error) {
        console.error('Error saving booking:', error);
        ElMessage.error(isEdit.value ? t('message.updateBookingFailed') : t('message.createBookingFailed'));
      }
    };
    
    // 重置表单
    const resetForm = () => {
      Object.assign(bookingForm, {
        bookingId: '',
        scheduleId: '',
        studentId: '',
        parentId: authStore.user?.roleId === 'PARENT' ? authStore.user.userId : '',
        status: 'PENDING'
      });
    };
    
    // 获取状态类型（用于标签样式）
    const getStatusType = (status) => {
      switch (status) {
        case 'PENDING': return 'warning';
        case 'CONFIRMED': return 'primary';
        case 'COMPLETED': return 'success';
        case 'CANCELLED': return 'danger';
        default: return 'info';
      }
    };
    
    // 获取状态标签
    const getStatusLabel = (status) => {
      switch (status) {
        case 'PENDING': return t('message.pending');
        case 'CONFIRMED': return t('message.confirmed');
        case 'COMPLETED': return t('message.completed');
        case 'CANCELLED': return t('message.cancelled');
        default: return status;
      }
    };
    
    // 根据状态获取操作类型
    const getActionTypeByStatus = (status) => {
      switch (status) {
        case 'PENDING': return 'success';
        case 'CONFIRMED': return 'warning';
        case 'COMPLETED': return 'info';
        case 'CANCELLED': return 'warning';
        default: return 'primary';
      }
    };
    
    // 根据状态获取操作文本
    const getActionTextByStatus = (status) => {
      switch (status) {
        case 'PENDING': return t('message.confirm');
        case 'CONFIRMED': return t('message.complete');
        case 'COMPLETED': return t('message.cancel');
        case 'CANCELLED': return t('message.reactivate');
        default: return t('message.update');
      }
    };
    
    // 格式化日期时间
    const formatDateTime = (dateTimeStr) => {
      if (!dateTimeStr) return '';
      const date = new Date(dateTimeStr);
      return date.toLocaleString();
    };
    
    // 格式化日期
    const formatDate = (dateStr) => {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      return date.toLocaleString();
    };
    
    onMounted(async () => {
      await Promise.all([
        loadAvailableSchedules()
      ]);
      loadBookings();
    });
    
    return {
      bookings,
      availableSchedules,
      dialogVisible,
      dialogTitle,
      bookingForm,
      bookingFormRef,
      bookingRules,
      statusOptions,
      openAddBookingDialog,
      viewBooking,
      editBooking,
      deleteBooking,
      updateBookingStatus,
      saveBooking,
      getStatusType,
      getStatusLabel,
      getActionTypeByStatus,
      getActionTextByStatus,
      formatDateTime,
      formatDate
    };
  }
};
</script>

<style scoped>
.booking-management {
  padding: 20px;
}

.booking-actions {
  margin-bottom: 20px;
}

.dialog-footer {
  text-align: right;
}

.table-cell-content {
  text-align: left;
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

/* 确保Element Plus表格内容左对齐 */
:deep(.el-table .cell) {
  text-align: left;
  padding-left: 10px;
}

/* 确保表格内容不会居中对齐 */
:deep(.el-table) {
  table-layout: fixed;
}

:deep(.el-table__body-wrapper) {
  text-align: left;
}
</style>